<template>
  <div class="chart-box" v-loading="loading">
    <!-- 暂无数据 -->
    <noData v-show="!hasData" :title="title" :subTitle="params.organizationName.value" />
    <!-- 年排放趋势 - Echart -->
    <div v-show="hasData" class="chart" ref="chartRef"></div>
  </div>
</template>

<script lang="ts" setup>
import { inject, ref, watch, computed, ComputedRef, onMounted } from 'vue';
import { useECharts } from '@/hooks/useECharts';
import { queryAnalysisYear } from '@/apis/eci/visualAnalysis';
import noData from '../../noData/index.vue';
import {
  queryAnalysisRes,
  queryAnalysisParams
} from '@/apis/eci/visualAnalysis/model/visualAnalysisModel';
import { kgToT } from '@/utils';
import { store } from '@/store';

interface injectParams {
  queryParams: queryAnalysisParams;
  organizationName: ComputedRef;
}

const loading = ref(false); // loading
const chartRef = ref(); // 年排放趋势 ref
const params = inject('params') as injectParams;
const isShowChartLine = computed(() => {
  return store.state.app.globalConfig.isShowChartLine;
});
console.log('*************************************', inject('params'));

const yearData = ref<queryAnalysisRes>({
  accumulateEmission: [],
  data: [],
  emissionStrength: [],
  totalEmission: [],
  startYear: '',
  endYear: ''
});

// 监听 queryParams 值如果发生变化重新发接口
watch(params.queryParams, async () => {
  loadYearData();
});
// 是否有展示数据
const hasData = computed(() => {
  if (yearData.value.totalEmission.length !== 0) {
    return true;
  } else {
    return false;
  }
});
// 请求年排放趋势接口
const loadYearData = async () => {
  try {
    if (params.queryParams.inventoryYear) {
      loading.value = true;
      const res: queryAnalysisRes = await queryAnalysisYear(params.queryParams);
      const accumulateEmission = handleArrayData(res.accumulateEmission);
      const emissionStrength = handleArrayData(res.emissionStrength);
      const totalEmission = handleArrayData(res.totalEmission);
      console.log('年碳排放趋势', res);
      yearData.value = {
        endYear: res.endYear,
        startYear: res.startYear,
        data: res.data,
        accumulateEmission,
        emissionStrength,
        totalEmission
      };
      renderChart(); // 渲染 echarts
    }
  } catch (error) {
    console.log(error);
  } finally {
    loading.value = false;
  }
};
// 处理数组数据单位
const handleArrayData = (arr: (string | number)[]) => {
  return arr.map(item => {
    return kgToT(Number(item));
  });
};
onMounted(() => {
  loadYearData(); // 请求年排放趋势接口
});
// 标题展示
const title = computed(() => {
  return yearData.value.startYear && yearData.value.endYear
    ? `${yearData.value.startYear}至${yearData.value.endYear}年碳排放量及强度趋势分析`
    : '暂无数据';
});
const { setOptions } = useECharts(chartRef);
// 年碳排放趋势 Echart
const annualTrendChart = () => {
  const colors = ['#7A8A99'];
  let option: any = {
    title: {
      text: `${yearData.value.startYear}至${yearData.value.endYear}年碳排放量及强度趋势分析`,
      subtext: params.organizationName.value,
      textStyle: {
        fontSize: 14,
        lineHeight: 22,
        fontFamily: 'PingFangSC, PingFang SC',
        color: '#0a1f33'
      },
      subtextStyle: {
        fontSize: 12,
        lineHeight: 20,
        color: colors[0],
        fontFamily: 'PingFangSC, PingFang SC'
      },
      padding: [
        0, // 上
        0, // 右
        0, // 下
        0 // 左
      ],
      itemGap: 0,
      left: 20,
      top: 15
    },
    legend: {
      right: 20,
      top: 15,
      // 设置上下的内边距为 5，左右的内边距为 10
      padding: [0, 0],
      orient: '',
      data: [
        {
          name: '碳排放量',
          itemStyle: {
            color: '#35BD9B'
          }
        },
        {
          name: '排放强度'
        }
      ]
    },
    color: colors,
    tooltip: {
      trigger: 'axis'
    },
    grid: {
      width: 'auto',
      height: 190,
      top: 115,
      left: 40,
      right: 55,
      bottom: 0,
      containLabel: true
    },
    dataZoom: [
      {
        show: true,
        startValue: 0,
        endValue: 10
      }
    ],
    // x 轴坐标配置
    xAxis: [
      {
        axisLabel: {
          color: '#7A8A99'
        },
        type: 'category',
        axisTick: {
          alignWithLabel: true
        },
        // prettier-ignore
        // data: ['2019年', '2019年', '2019年', '2019年', '2019年']
        // 年份x轴数据
        data:yearData.value.data
      }
    ],
    // y 轴坐标配置
    yAxis: [
      // 排放量
      {
        nameTextStyle: {
          // align: 'center'
        },
        type: 'value',
        name: '排放量(tCO₂e)',
        position: 'left',
        offset: 20,
        splitNumber: 5, // 设置分几段显示
        alignTicks: true,
        axisLine: {
          show: false,
          lineStyle: {
            color: colors[0]
          }
        },
        splitLine: {
          show: isShowChartLine.value ?? true
        }
      },
      // 排放强度
      {
        type: 'value',
        name: '排放强度(tCO₂e/台)',
        position: 'right',
        offset: 20,
        splitNumber: 5, // 设置分几段显示
        alignTicks: true,
        axisLine: {
          show: false,
          lineStyle: {
            color: colors[0]
          }
        },
        splitLine: {
          show: isShowChartLine.value ?? true
        }
      }
    ],
    series: [
      // 排放量
      {
        name: '碳排放量',
        type: 'bar',
        // data: [270, 260, 600, 450, 2000],
        data: yearData.value.totalEmission, // 总碳排放量
        yAxisIndex: 0,
        barCategoryGap: 2,
        barWidth: 28,
        itemStyle: {
          borderRadius: [2, 2, 0, 0], //（顺时针左上，右上，右下，左下）
          color: '#35BD9B'
        }
      },
      // 排放强度
      {
        name: '排放强度',
        type: 'line',
        yAxisIndex: 1,
        // data: [150, 250, 300, 400, 450],
        data: yearData.value.emissionStrength, // 排放强度
        itemStyle: {
          color: '#4FBAF3'
        }
      }
    ]
  };

  return option;
};
function renderChart() {
  const option = annualTrendChart();
  setOptions(option);
}
</script>

<style lang="scss" scoped>
.chart-box {
  margin-top: 16px;
  height: 360px;
  background: #ffffff;
  box-shadow: 0px 2px 4px 0px rgba(67, 89, 112, 0.08);
  border-radius: 6px;

  .chart {
    width: 100%;
    height: 100%;
    &::after {
      position: absolute;
      top: 70px;
      left: 0;
      background-color: #ebeff2;
      height: 1px;
      width: 100%;
      content: '';
    }
  }
}
.flex-box {
  position: relative;
  margin-top: 16px;
  height: 320px;
  background: #ffffff;
  box-shadow: 0px 2px 4px 0px rgba(67, 89, 112, 0.08);
  border-radius: 6px;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
